package com.ansion.utils;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ansion.BridgeCallback;
import com.ansion.BridgeInterface;
import com.ansion.basetool.preconditions.Preconditions;
import com.ansion.log.VLog;
import com.ansion.utils.file.FileMimeTypes;
import com.ansion.utils.file.SFileProvider;

import java.io.File;

public class IntentUtils {
    public static boolean isActivityAvailable(@NonNull Context context, @NonNull Intent intent) {
        return context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null;
    }

    public static void startActivity(@NonNull Context context, @NonNull Intent intent) {
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (!isActivityAvailable(context, intent)) {
            VLog.w("TAG_BASE_MISC", "No activity found: %s. Cannot start.", intent);
        }
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            VLog.e("TAG_BASE_MISC", "No activity found: %s. Cannot start.", intent);
        }
    }

    public static void startActivity(@NonNull Context context, @NonNull Class<?> cls) {
        startActivity(context, cls, null);
    }

    public static void startActivity(@NonNull Context context, @NonNull Class<?> cls, @Nullable Bundle args) {
        startActivity(context, cls, false, args);
    }

    public static void startActivity(@NonNull Context context, @NonNull Class<?> cls, boolean clearTop, @Nullable Bundle args) {
        Intent intent = new Intent(context, cls);
        if (args != null) {
            intent.putExtras(args);
        }
        if (clearTop) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void startActivityForResult(@NonNull Context context, @NonNull Class<?> cls, @Nullable Bundle args, BridgeCallback callback) {
        Intent intent = new Intent(context, cls);
        if (args != null) {
            intent.putExtras(args);
        }
        startActivityForResult(context, intent, callback);
    }

    public static void startActivityForResult(@NonNull Context context, @NonNull Intent intent, BridgeCallback callback) {
        BridgeInterface.getFragment(context).startActivityForResult(intent, callback);
    }

    public static boolean openFile(@NonNull Context context, @NonNull String path) {
        Preconditions.checkNotNull(context);
        Preconditions.checkNotEmpty(path);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        File file = new File(path);
        String type = FileMimeTypes.getMimeTypeForIntent(file);
        boolean unknownType = type.equals("*/*");
        intent = formatFileProviderIntent(file, intent, type, unknownType);
        return startFileIntent(context, intent, type);
    }

    public static boolean startFileIntent(Context context, Intent intent, String type) {
        boolean startOk = false;
        try {
            context.startActivity(intent);
            startOk = true;
        } catch (Exception e) {
            VLog.i("TAG_BASE_MISC", "Failed to open file through activity. %s", e.getMessage());
        }

        if (!startOk) {
            if ("*/*".equals(type)) {
                return false;
            } else {
                intent.setType("*/*");
                return startFileIntent(context, intent, type);
            }
        }
        return true;
    }

    public static Intent formatFileProviderIntent(File file, Intent intent,
                                                  String intentType, boolean unknownType) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, intentType);
        } else {
            Uri uri = SFileProvider.getUriForFile(file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(uri, intentType);
        }
        if (unknownType) {
            return Intent.createChooser(intent, null);
        } else {
            return intent;
        }
    }

    public static Intent getSystemAppSettings(@NonNull Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        return intent;
    }
}
